package com.zimi.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.mapper.SysCodeMapper;
import com.zimi.model.SysCode;
import com.zimi.model.SysUser;
import com.zimi.util.Pinyin;
import com.zimi.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysCodeService {

    @Autowired
    private SysCodeMapper sysCodeMapper;


    public int insert(SysCode record) {
        SysUser user = UserUtil.getUser();

        record.setCreateUser(user.getId());
        record.setCreateTime(new Date());

        return sysCodeMapper.insert(record);
    }

    public SysCode selectById(int id) {
        SysCode result = sysCodeMapper.selectById(id);
        return result;
    }

    public int insertSelective(SysCode record) {
        SysUser user = UserUtil.getUser();

        record.setCreateUser(user.getId());
        record.setCreateTime(new Date());
        return sysCodeMapper.insert(record);
    }

    public int update(SysCode record) {
        //1)对该条记录进行行加锁
        SysCode lockRecord = sysCodeMapper.selectOne(new QueryWrapper<SysCode>().lambda().eq(SysCode::getId, record.getId()).last("for update"));

        // 2）判断该数据已经被改过没有
        if (lockRecord.getUpdateTime() != null) {
            if (record.getUpdateTime() == null) {
                throw new RuntimeException("更新数据失败，数据已经被其他用户改过。");
            } else {
                if (record.getUpdateTime().getTime() != lockRecord.getUpdateTime().getTime()) {
                    throw new RuntimeException("更新数据失败，数据已经被其他用户改过。");
                }
            }
        }
        //3)对该记录进行更新
        SysUser user = UserUtil.getUser();

        record.setUpdateUser(user.getId());
        record.setUpdateTime(new Date());

        return sysCodeMapper.updateById(record);
    }


    public List<SysCode> selectAll(SysCode record) {
        List<SysCode> list = sysCodeMapper.selectList(new LambdaQueryWrapper<SysCode>().ne(SysCode::getCodeState, 2).orderByAsc(SysCode::getCodeSort));
        return list;
    }

    /**
     * 新增字典数据
     *
     * @param record
     * @return
     */
    public int saveNewSysCode(SysCode record) {

        SysUser user = UserUtil.getUser();

        record.setCreateUser(user.getId());
        record.setCreateTime(new Date());

        //查询是否重复
        SysCode tempSc = new SysCode();
        tempSc.setCodeName(record.getCodeName());
        record.setCodeState(1);
        if (record.getCodeRoot() != null && record.getCodeRoot() == 1) {
            tempSc.setCodeRoot(1);
        }
        if (record.getCodeIsParent() != null && record.getCodeIsParent() == 1) {
            tempSc.setCodeIsParent(1);
        } else {
            tempSc.setParentId(record.getParentId());
        }

        List<SysCode> scList = sysCodeMapper.selectList(new QueryWrapper(record));
        ;
        if (scList != null && scList.size() > 0) {
            return 0;
        }

        if (record.getCodeRoot() != null && record.getCodeRoot() == 1) {//根节点
            record.setCodeTypeName(Pinyin.getPinYin(record.getCodeName()));
            record.setCodeType(Pinyin.getPinYinHeadChar(record.getCodeName()));
            record.setCodeIsParent(1);
        }
        if (record.getParentId() != null && record.getParentId() > 0) {

            SysCode code = new SysCode();
            code.setParentId(record.getParentId());
            List<SysCode> list = sysCodeMapper.selectList(new QueryWrapper(code));
            if (list != null && list.size() > 0) {
                int sort = 0;
                for (SysCode temp : list) {
                    if (temp.getCodeSort() != null && temp.getCodeSort() > sort) {
                        sort = temp.getCodeSort();
                    }
                }
                record.setCodeSort(sort + 1);
            }
        } else {
            SysCode code = new SysCode();
            code.setCodeIsParent(1);
            List<SysCode> list = sysCodeMapper.selectList(new QueryWrapper(code));
            if (list != null && list.size() > 0) {
                int sort = 0;
                for (SysCode temp : list) {
                    if (temp.getCodeSort() != null && temp.getCodeSort() > sort) {
                        sort = temp.getCodeSort();
                    }
                }
                record.setCodeSort(sort + 1);
            }

        }

        if (record.getCodeRoot() != null && record.getCodeRoot() == 2 && record.getCodeIsParent() != null && record.getCodeIsParent() == 1) {
            record.setCodeTypeName(Pinyin.getPinYin(record.getCodeName()));
        }
        sysCodeMapper.insert(record);

        if (record.getParentId() != null && record.getParentId() > 0) {
            SysCode sc = sysCodeMapper.selectById(record.getParentId());
            SysCode sysCode = sysCodeMapper.newestCodeId();
            sysCode.setCodePath(sc.getCodePath() + "/" + sysCode.getId());
            this.update(sysCode);
        } else {
            SysCode sysCode = sysCodeMapper.newestCodeId();
            sysCode.setCodePath("/" + sysCode.getId());
            this.update(sysCode);

        }

        return 1;

    }


    /**
     * 删除
     *
     * @param record
     * @return
     */
    public int delSysCode(SysCode record) {
        //1)行加锁
        SysCode lockRecord = sysCodeMapper.selectOne(new QueryWrapper<SysCode>().lambda().eq(SysCode::getId, record.getId()).last("for update"));

        // 2）判断该数据已经被改过没有
        if (lockRecord.getUpdateTime() != null) {
            if (record.getUpdateTime() == null) {
                throw new RuntimeException("更新数据失败，数据已经被其他用户改过。");
            } else {
                if (record.getUpdateTime().getTime() != lockRecord.getUpdateTime().getTime()) {
                    throw new RuntimeException("更新数据失败，数据已经被其他用户改过。");
                }
            }
        }
        //3)对该记录进行更新
        SysUser user = UserUtil.getUser();

        record.setUpdateUser(user.getId());
        record.setUpdateTime(new Date());


        SysCode code = new SysCode();
        code.setParentId(record.getId());
        List<SysCode> list = sysCodeMapper.selectList(new QueryWrapper(code));
        if (list != null && list.size() > 0) {
            return 0;
        } else {
            return sysCodeMapper.deleteById(record);
        }

    }

    /**
     * 保存修改后的数据
     *
     * @param record
     * @return
     */
    public int updateCode(SysCode record) {

        //1)行加锁
        SysCode lockRecord = sysCodeMapper.selectOne(new QueryWrapper<SysCode>().lambda().eq(SysCode::getId, record.getId()).last("for update"));

        // 2）判断该数据已经被改过没有
        if (lockRecord.getUpdateTime() != null) {
            if (record.getUpdateTime() == null) {
                throw new RuntimeException("更新数据失败，数据已经被其他用户改过。");
            } else {
                if (record.getUpdateTime().getTime() != lockRecord.getUpdateTime().getTime()) {
                    throw new RuntimeException("更新数据失败，数据已经被其他用户改过。");
                }
            }
        }
        //3)对该记录进行更新
        SysUser user = UserUtil.getUser();

        record.setUpdateUser(user.getId());
        record.setUpdateTime(new Date());

        //查询是否重复
        SysCode tempSc = new SysCode();
        tempSc.setCodeName(record.getCodeName());
        tempSc.setId(record.getId());
        tempSc.setCodeRoot(record.getCodeRoot());
        tempSc.setCodeIsParent(record.getCodeIsParent());
        tempSc.setParentId(record.getParentId());
        List<SysCode> scList = sysCodeMapper.selectList(new QueryWrapper(tempSc));
//        if(scList != null && scList.size() > 0){
//            return 0;
//        }

//        System.out.println(record.getParentId());
        SysCode parentCode = null;
        if (record.getParentId() != null) {
            int parentId = record.getParentId();
            parentCode = sysCodeMapper.selectById(parentId);
        }

        if (parentCode != null) {
            record.setParentId(parentCode.getId());
            record.setCodePath(parentCode.getCodePath() + "/" + record.getId());
        }
        if (record.getCodeRoot() != null && record.getCodeRoot() == 1) {   //处理根节点
            record.setCodeTypeName(Pinyin.getPinYin(record.getCodeName()));
            record.setCodeType(Pinyin.getPinYinHeadChar(record.getCodeName()));
            record.setCodeIsParent(1);
            //查询该节点修改前的数据
            SysCode sc = sysCodeMapper.selectById(record.getId());

        } else {
            if (record.getCodeIsParent() != null && record.getCodeIsParent() == 1) {  //处理父节点
                record.setCodeTypeName(Pinyin.getPinYin(record.getCodeName()));
            } else {  //不是父节点，取父节点的标识
                record.setCodeTypeName(parentCode.getCodeTypeName());
            }
        }
        return sysCodeMapper.updateById(record);
    }

}
